#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include <unistd.h>
#include <sys/wait.h>

#include "codegen/codegen.h"
#include "dump/ast.dump.h"

extern int yydebug;
extern FILE *yyin;
extern int yyparse();
extern ProgramAST* root;

int main(int argc, char *argv[])
{
    yydebug = 0;
    yyin = fopen(argv[1], "r");
	if(argc > 1 && (yyin == NULL)) {
		fprintf(stderr, "can not open %s\n", argv[1]);
		exit(1);
	}
    yyparse();
    if (nullptr == root) {
        exit(1);
    }

    // auto dump = std::make_unique<ASTDump>();
    // dump->visit(root);

	auto codegen = std::make_unique<CodeGen>();
    codegen->visit(root);

    std::string file{argv[1]};
    if (file.substr(file.find_last_of('.')) == ".pas") {
        file = file.substr(0, file.find_last_of('.'));
    }
    codegen->write(file + ".bc");
    if (fork() == 0) {
        execlp("llc", "llc", (file + ".bc").c_str(), NULL);
    }
    if (fork() == 0) {
        execlp("clang++", "clang++", "-o", (file + ".out").c_str(), (file + ".s").c_str(), NULL);
    }

    return 0;
}
